package com.example.lianguisystem.controller;

import com.example.lianguisystem.DTO.BaoGongDTO;
import com.example.lianguisystem.VO.DailyCapacityVO;
import com.example.lianguisystem.common.Result;
import com.example.lianguisystem.entity.DailyCapacity;
import com.example.lianguisystem.entity.LianGuiLabelStatus;
import com.example.lianguisystem.entity.statistics.ICombin;
import com.example.lianguisystem.entity.statistics.ICombindetail;
import com.example.lianguisystem.mapperLianGui.*;
import com.example.lianguisystem.mapperLianGui.statistics.*;
import com.example.lianguisystem.service.CommonService;
import com.example.lianguisystem.service.DailyCapacityService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/baoGong")
@CrossOrigin
@Slf4j
public class BaoGongController {
    @Autowired
    private BaoGongMapper baoGongMapper;


    @Autowired
    private LabelStatusMapper labelStatusMapper;

    @Autowired
    private DailyCapacityMapper dailyCapacityMapper;
    @Autowired
    private LabelMapper labelMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private DailyCapacityService dailyCapacityService;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private MnfFinishedMapper mnfFinishedMapper;
    @Autowired
    private MnfFinisheditemMapper mnfFinisheditemMapper;
    @Autowired
    private MnfFinisheddetailMapper mnfFinisheddetailMapper;
    @Autowired
    private ICombinMapper iCombinMapper;
    @Autowired
    private ICombindetailMapper iCombindetailMapper;


    //    @GetMapping("/scan")
//    public Result scan(@RequestParam("label") String label, @RequestParam("username") String username) {
//        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectByLabel(label);
//        if (lianGuiLabelRecord == null) {
//            return Result.fail("请扫描重量标签");
//        }
////        if (!lianGuiLabelRecord.getCreateBy().equals(username)) {
////            return Result.fail("只允许扫本人打印的标签");
////        }
//        return Result.success(lianGuiLabelRecord);
//    }
    @GetMapping("/scan")
    public Result scan(@RequestParam("label") String label, @RequestParam("username") String username) {
        DailyCapacityVO lianGuiLabelRecord = labelMapper.selectByLabelOfDaily(label);
        if (lianGuiLabelRecord == null) {
            return Result.fail("请扫描重量标签");
        }
        Integer integer = labelMapper.selectLabelStatusOfThree(label);
        if (integer <= 0) {
            return Result.success(lianGuiLabelRecord);
        }
        return Result.fail("标签已报工");
    }

    @GetMapping("/list")
    public Result list(@RequestParam("username") String username, @RequestParam("recordDate") String recordDate) {
        List<LianGuiLabelStatus> lianGuiLabelStatuses = labelStatusMapper.selectLabelStatusOfBaoGong(username, recordDate);
        return Result.success(lianGuiLabelStatuses);
    }

//    @PostMapping("/baoGong")
//    public Result baoGong(@RequestBody List<LianGuiLabelRecord> detailList) {
//        List<String> collect = detailList.stream().map(LianGuiLabelRecord::getId).collect(Collectors.toList());
//        List<LianGuiLabelRecord> list = labelMapper.selectLianGuiLabelById(collect);
//        if (list.size() > 0) {
//            collect = list.stream().map(LianGuiLabelRecord::getLabel).collect(Collectors.toList());
//            return Result.fail("只允许扫未入库标签: " + collect);
//        }
//
//        for (LianGuiLabelRecord detail : detailList) {
//            LianGuiLabelRecord lianGuiLabelRecord = new LianGuiLabelRecord();
//            lianGuiLabelRecord.setStatus((byte) 5);
//            lianGuiLabelRecord.setId(detail.getId());
//            labelMapper.updateById(lianGuiLabelRecord);
//            LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
//            lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
//            lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
//            lianGuiLabelStatus.setRecordDate(new Date());
//            lianGuiLabelStatus.setRecordBy(detail.getCreateBy());
//            labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
//        }
//
//        return Result.success();
//    }
Logger logger = LoggerFactory.getLogger(LianGuiLabelController.class);

    @GetMapping("/testLog")
    public Result testLog() {
        logger.error("错误提示");
        return Result.success();
    }

    @PostMapping("/baoGong")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    public Result baoGong(@RequestBody List<BaoGongDTO> detailList, @RequestParam("username") String username) {
        for (BaoGongDTO baoGongDTO : detailList) {
            List<DailyCapacityVO> recodeList = baoGongDTO.getList();
            List<String> tempLabelIdList = recodeList.stream().map(DailyCapacityVO::getLabelId).collect(Collectors.toList());
            Integer integer = dailyCapacityMapper.selectLabelStatusByIdList(tempLabelIdList);
            if (integer > 0) {
                return Result.fail("只允许提交未入库和已销售的标签");
            }
        }

        for (BaoGongDTO baoGongDTO : detailList) {
            String title = baoGongDTO.getTitle();
            String subTitle = baoGongDTO.getSubTitle();
            List<DailyCapacityVO> recodeList = baoGongDTO.getList();
            List<String> tempLabelIdList = recodeList.stream().map(DailyCapacityVO::getLabelId).collect(Collectors.toList());
            Integer integer = dailyCapacityMapper.selectLabelStatusByIdList(tempLabelIdList);
            if (integer > 0) {
                return Result.fail("只允许提交未入库和已销售的标签");
            }
            List<DailyCapacityVO> checkAcceptList = recodeList.stream().filter(item -> item.getCpTypeNo().contains("分切")).collect(Collectors.toList());
//            List<DailyCapacityVO> assemblyList = recodeList.stream().filter(item -> !item.getCpTypeNo().contains("分切")).collect(Collectors.toList());
            List<DailyCapacityVO> assemblyList = recodeList;
            Map<String, Object> userDataMap = commonMapper.selectUserData(username);
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localDate = LocalDate.now();
            ZonedDateTime zdt = localDate.atStartOfDay(zoneId);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


            // 3. 转换为 Date 对象 (添加时区信息)
            Date dateValue = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

            DateTimeFormatter tempDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = LocalDate.now().format(tempDtf);
            Date date = Date.from(zdt.toInstant());
//            if (checkAcceptList.size() > 0) {
//                Set<String> collect = checkAcceptList.stream().map(DailyCapacityVO::getSalesOrderId).collect(Collectors.toSet());
//                List<SalesOrder> salesOrders = dailyCapacityMapper.selectSalesOrderByIdSet(collect);
//                for (SalesOrder salesOrder : salesOrders) {
//                    double sum = checkAcceptList.stream().filter(item -> item.getSalesOrderId().equals(salesOrder.getId())).mapToDouble(DailyCapacityVO::getWeight).sum();
//                    salesOrder.setCollectQty(sum);
//                }
//                MnfFinished mnfFinished = dailyCapacityService.getMnfFinished(dateValue, salesOrders.get(0).getProcessingBillid(), userDataMap, checkAcceptList.get(0).getMachine());
//                List<MnfFinisheditem> mnfFinisheditemList = dailyCapacityService.getMnfFinisheditem(date, salesOrders);
//                List<MnfFinisheddetail> mnfFinisheddetailList = dailyCapacityService.getMnfFinisheddetail(mnfFinisheditemList);
//                String pre = "MF-";
//                List<String> salesOrderIdList = salesOrders.stream().map(SalesOrder::getId).collect(Collectors.toList());
//                synchronized (this) {
//                    String mfBillcode = commonService.getBillCode(pre, "mnf_finished");
//                    Integer mfBillid = commonMapper.selectMaxBiillidByTableName("mnf_finished");
//                    mnfFinished.setBillid(mfBillid);
//                    mnfFinished.setBillcode(mfBillcode);
//                    mnfFinishedMapper.insert(mnfFinished);
//                    for (MnfFinisheditem mnfFinisheditem : mnfFinisheditemList) {
//                        mnfFinisheditem.setBillid(mfBillid);
//                        mnfFinisheditemMapper.insert(mnfFinisheditem);
//                    }
//                    for (MnfFinisheddetail mnfFinisheddetail : mnfFinisheddetailList) {
//                        mnfFinisheddetail.setBillid(mfBillid);
//                        mnfFinisheddetailMapper.insert(mnfFinisheddetail);
//                    }
//                    commonMapper.execup_ab_billprint_insert(41, mfBillid, mfBillcode, format, mnfFinished.getOpid(), mnfFinished.getShopid());
//                    DailyCapacity dailyCapacity = new DailyCapacity();
//                    dailyCapacity.setBillid(mfBillid);
//                    dailyCapacity.setBillcode(mfBillcode);
//                    dailyCapacity.setBillType("验收单");
//                    dailyCapacity.setCreateBy(username);
//                    dailyCapacity.setCreateDate(new Date());
//                    dailyCapacityMapper.insert(dailyCapacity);
//
//                    List<String> temp = checkAcceptList.stream().map(DailyCapacityVO::getLabelId).collect(Collectors.toList());
//                    dailyCapacityMapper.updateLabelRecordBillById(temp, dailyCapacity.getId());
//                }
//            }
            if (assemblyList.size() > 0) {
                List<List<DailyCapacityVO>> collect = assemblyList.stream().collect(Collectors.groupingBy(vo -> vo.getDesignNo() +
                        "|" + vo.getMachine() +
                        "|" + vo.getWorkshop() +
                        "|" + vo.getPrintPerson() +
                        "|" + vo.getPrintDate2()
                ))
                        .values().stream().collect(Collectors.toList());
                List<ICombin> iCombinList = dailyCapacityService.getICombin(userDataMap, collect);
                Map<ICombin, List<ICombindetail>> iCombinMap = dailyCapacityService.getICombindetail(iCombinList);
                for (Map.Entry<ICombin, List<ICombindetail>> entry : iCombinMap.entrySet()) {
                    ICombin iCombin = entry.getKey();
                    List<ICombindetail> iCombindetailList = entry.getValue();
                    if (iCombindetailList.size() <= 0) {
                        throw new RuntimeException("单身内容为空，请联系IT查找原因，品号ID："+iCombin.getGoodsid());
                    }
                    String pre = "CO-";
                    synchronized (this) {
                        String coBillcode = commonService.getBillCode(pre, "i_combin");
                        Integer coBillid = commonMapper.selectMaxBiillidByTableName("i_combin");
                        iCombin.setBillid(coBillid);
                        iCombin.setBillcode(coBillcode);
                        iCombinMapper.insert(iCombin);
                        for (ICombindetail iCombindetail : iCombindetailList) {
                            iCombindetail.setBillid(coBillid);
                            iCombindetailMapper.insert(iCombindetail);
                        }
                        commonMapper.execup_ab_billprint_insert(27, coBillid, coBillcode, format, iCombin.getOpid(), iCombin.getShopid());
                        DailyCapacity dailyCapacity = new DailyCapacity();
                        dailyCapacity.setBillid(coBillid);
                        dailyCapacity.setBillcode(coBillcode);
                        dailyCapacity.setBillType("组装单");
                        dailyCapacity.setCreateBy(username);
                        dailyCapacity.setCreateDate(new Date());
                        dailyCapacityMapper.insert(dailyCapacity);
                        List<DailyCapacityVO> list = iCombin.getList();
                        List<String> temp = list.stream().map(DailyCapacityVO::getLabelId).collect(Collectors.toList());
                        dailyCapacityMapper.updateLabelRecordBillById(temp, dailyCapacity.getId());
                    }
                }
                List<String> labelIdList = assemblyList.stream().map(DailyCapacityVO::getLabelId).collect(Collectors.toList());
//            dailyCapacityMapper.updateLabelRecordStatisticsStatusById(labelIdList);
            }
            dailyCapacityMapper.updateLabelRecordStatusById(tempLabelIdList);
            for (String labelId : tempLabelIdList) {
                LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
                lianGuiLabelStatus.setLabelId(labelId);
                lianGuiLabelStatus.setStatus((byte) 3);
                lianGuiLabelStatus.setRecordDate(new Date());
                lianGuiLabelStatus.setRecordBy(username);
                labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
            }
        }

//        List<String> collect = detailList.stream().map(LianGuiLabelRecord::getId).collect(Collectors.toList());
//        List<LianGuiLabelRecord> list = labelMapper.selectLianGuiLabelById(collect);
//        if (list.size() > 0) {
//            collect = list.stream().map(LianGuiLabelRecord::getLabel).collect(Collectors.toList());
//            return Result.fail("只允许扫未入库标签: " + collect);
//        }
//
//        for (LianGuiLabelRecord detail : detailList) {
//            LianGuiLabelRecord lianGuiLabelRecord = new LianGuiLabelRecord();
//            lianGuiLabelRecord.setStatus((byte) 5);
//            lianGuiLabelRecord.setId(detail.getId());
//            labelMapper.updateById(lianGuiLabelRecord);
//            LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
//            lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
//            lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
//            lianGuiLabelStatus.setRecordDate(new Date());
//            lianGuiLabelStatus.setRecordBy(detail.getCreateBy());
//            labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
//        }
//        int i = 1 / 0;
        return Result.success();
    }
}
